package com.guilimall.cart.Service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.common.utils.R;
import com.guilimall.cart.Service.CartService;
import com.guilimall.cart.feign.ProductFeigService;
import com.guilimall.cart.interceptor.CartInterceptor;
import com.guilimall.cart.vo.Cart;
import com.guilimall.cart.vo.CartItem;
import com.guilimall.cart.vo.SkuInfo;
import com.guilimall.cart.vo.UserInfoTo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

@Slf4j
@Service
public class CartServiceImpl implements CartService {
    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    ProductFeigService productFeigService;

    @Autowired
    ThreadPoolExecutor executor;

    private final String CART_PREFIX = "gulimall:cart:";


    @Override
    public List<CartItem> getCurrentUserCartItems() {
        UserInfoTo userInfoTo = CartInterceptor.toThreadLocal.get();
        if (userInfoTo.getUserId() == null){
            return null;
        }else {
            String Userkey = CART_PREFIX+userInfoTo.getUserId();
            List<CartItem> cartItems = getCartItem(Userkey);
            List<CartItem> collect = cartItems.stream().filter(item -> item.getCheck())
                    .map(cartItem -> {
                        R r = productFeigService.getPrice(cartItem.getSkuId());
                        if (r.getCode() == 0){
                            //更新价格
                            String price = (String)r.get("data");
                            cartItem.setPrice(new BigDecimal(price));
                        }
                        return cartItem;
                    })
                    .collect(Collectors.toList());

            return collect;
        }
    }

    /**
     * 获取购物车
     * @return
     */
    @Override
    public Cart getCart() throws ExecutionException, InterruptedException {
        UserInfoTo userInfoTo = CartInterceptor.toThreadLocal.get();
        Cart cart = new Cart();
        if (userInfoTo.getUserId() != null){
            //登录状态
            String Userkey = CART_PREFIX+userInfoTo.getUserKey();
            List<CartItem> cartItems1 = getCartItem(Userkey);
            //如果临时购物车有数据，需要把临时购物车的数据放入登录id
            if (cartItems1 != null){
                for (CartItem cartItem : cartItems1) {
                    //合并
                    addToCart(cartItem.getSkuId(),cartItem.getCount());
                }
                clearCart(Userkey); //清空临时购物车
            }
            String key = CART_PREFIX+userInfoTo.getUserId();
            List<CartItem> cartItems2 = getCartItem(key);
            cart.setItems(cartItems2);
        }else {
            //无登录
            String key = CART_PREFIX+userInfoTo.getUserKey();
            List<CartItem> cartItems = getCartItem(key);
            cart.setItems(cartItems);
        }
        return cart;
    }

    /**
     * 删除购物项
     * @param skuId
     */
    @Override
    public void deleteItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.delete(skuId.toString().toString());
    }

    /**
     * 修改购物项数量
     * @param skuId
     * @param count
     */
    @Override
    public void countNum(Long skuId, Integer count) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCount(count);
        cartOps.put(skuId.toString(),JSON.toJSONString(cartItem));
    }

    /**
     * 勾选购物项
     * @param skuId
     * @param check
     */
    @Override
    public void checkItem(Long skuId, Integer check) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCheck(check == 1);
        cartOps.put(skuId.toString(),JSON.toJSONString(cartItem));
    }

    /**
     * 清空购物车
     */
    @Override
    public void  clearCart(String cartKey){
        redisTemplate.delete(cartKey);
    }

    /**
     * 获取购物车里的所有信息
     * @param key
     * @return
     */
    public  List<CartItem> getCartItem(String key){
        BoundHashOperations<String, Object, Object> operations = redisTemplate.boundHashOps(key);
        List<Object> values = operations.values();
        if (values!=null && values.size()>0) {
            List<CartItem> collect = values.stream().map(value -> {
                String str = (String) value;
                return JSON.parseObject(str,CartItem.class);
            }).collect(Collectors.toList());
           return  collect;
        }
        return null;
    }

    /**
     * 获取购物车里的单个信息
     * @param skuId
     * @return
     */
    @Override
    public CartItem getCartItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String cart = (String) cartOps.get(skuId.toString());
        return JSON.parseObject(cart,CartItem.class);
    }

    @Override
    public CartItem addToCart(Long skuId, Integer num) throws ExecutionException, InterruptedException {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String res = (String) cartOps.get(skuId.toString());

        if (StringUtils.isEmpty(res)){
            //购物车无此商品
            //添加新商品信息到购物车
            CartItem cartItem = new CartItem();
            CompletableFuture<Void> getSkuInfoTask = CompletableFuture.runAsync(() -> {
                //1.远程查询当前商品的信息
                R r = productFeigService.getSkuInfo(skuId);
                SkuInfo skuInfo = new SkuInfo();
                if (r.getCode() == 0) {
                    skuInfo = r.getData("skuInfo", new TypeReference<SkuInfo>() {
                    });
                }

                cartItem.setCheck(true);
                cartItem.setCount(num);
                cartItem.setImages(skuInfo.getSkuDefaultImg());
                cartItem.setTitle(skuInfo.getSkuTitle());
                cartItem.setSkuId(skuId);
                cartItem.setPrice(skuInfo.getPrice());
            }, executor);

            //2.远程查询sku的属性信息
            CompletableFuture<Void> getSkuSaleAttrValues = CompletableFuture.runAsync(() -> {
                List<String> skuSaleAttrValues = productFeigService.getSkuSaleAttrValues(skuId);
                cartItem.setSkuAttr(skuSaleAttrValues);
            }, executor);
            CompletableFuture.allOf(getSkuInfoTask,getSkuSaleAttrValues).get();
            cartOps.put(skuId.toString(), JSON.toJSONString(cartItem));
            return cartItem;
        }else {
            //购物车有此商品
            CartItem cartItem = JSON.parseObject(res, CartItem.class);
            cartItem.setCount(cartItem.getCount() + num);
            cartOps.put(skuId.toString(),JSON.toJSONString(cartItem));
            return cartItem;
        }





    }

    /**
     * 获取到我们要操作的购物车
     * @return
     */
    public BoundHashOperations<String, Object, Object> getCartOps() {
        UserInfoTo userInfoTo = CartInterceptor.toThreadLocal.get();

        String catKey = ""; //购物车
        if (userInfoTo.getUserId() == null){
            //临时购物车
            catKey = CART_PREFIX + userInfoTo.getUserKey();
        }else {
            catKey = CART_PREFIX + userInfoTo.getUserId();
        }
        //当前购物车是否有此商品
        return redisTemplate.boundHashOps(catKey);
    }
}
